<template>
  <div class="PlatformNewsbox">
    <div class="topbox">
      <div class="leftspan">
        <span>消息标题</span>
        <span><el-input v-model="title" placeholder="请输入消息标题" size="small"></el-input></span>
      </div>
      <div>
        <el-button size="small" @click="chongzhi">重置</el-button>
        <el-button type="primary" size="small" @click="xiangqinglist">查询</el-button>
      </div>
    </div>
    <div class="bodybox">
      <div class="title">
        <div>平台消息中心</div>
        <div class="butexp">
          <el-button type="primary" size="small" class="moban" @click="addnews">新增</el-button>
           <TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile>
        </div>
      </div>
      <!-- table表格 -->
      <div class="table">
        <el-table
          ref="table"
          :size="issize"
          border
          :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
          v-loading="loading"
          height="calc(100% - 1px)"
          style="width: 100%"
          :data="tableData">
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="messageTitle"
            label="标题">
          </el-table-column>
          <el-table-column
            prop="messageTypeName"
            label="消息类型">
          </el-table-column>
          <el-table-column
            prop="messageSender"
            label="发送人员">
          </el-table-column>
          <el-table-column
            prop="messageState"
            align="center"
            label="消息状态">
            <template #default="{row}">
              <div>
                <span class="status" :style="{'background-color':row.messageState=='1'?'#7d9d05':row.messageState=='2'?'#f2bd42':'#007cee'}">
                  {{ row.messageState=='1'?'已发送':row.messageState=='2'?'已撤回':'已创建' }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            width="160"
            label="创建时间">
          </el-table-column>
          <el-table-column
            align="center"
            width="160"
            prop="sendTime"
            label="发送时间">
          </el-table-column>
          <el-table-column
            align="center"
            width="160"
            prop="recoverTime"
            label="撤回时间">
          </el-table-column>
          <el-table-column
            prop="hasAttachmentName"
            label="是否有附件">
          </el-table-column>
          <el-table-column
            prop="messageContent"
            label="消息内容">
            <template #default="{row}">
              <span v-html="row.messageContent"></span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="address"
            label="操作">
            <template #default="{row}">
              <span>
                <el-tooltip class="item" effect="dark" content="浏览" placement="top">
                  <i @click="bianji(row,'look')" class="el-icon-view" style="color: #1a90fe;cursor: pointer;"></i>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="发布" placement="top">
                  <i v-if="!row.messageState=='1'||row.messageState=='2'" @click="delnews(row,'fabu')" class="iconfont icon-fabu-xianxingtubiao-01" style="color: #7d9d05;cursor: pointer;"></i>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="撤销" placement="top">
                  <i v-if="row.messageState=='1'" @click="delnews(row,'cexiao')" class="iconfont icon-chexiao6" style="color: #f2bd42;cursor: pointer;"></i>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                  <i v-if="!row.messageState=='1'||row.messageState=='2'" @click="bianji(row)" class="el-icon-edit" style="color: #1a90fe;cursor: pointer;"></i>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <i v-if="!row.messageState=='1'||row.messageState=='2'" @click="delnews(row,'shanchu')"  class="el-icon-delete" style="color: red;cursor: pointer;"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部分页 -->
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageobj.pageNo"
          :page-size="20"
          @current-change="xiangqinglist"
          :total="+totalCounts">
        </el-pagination>
      </div>
      <div class="dialog">
        <el-dialog
          :title="form.messageId&&!isshow?'编辑':form.messageId&&isshow?'浏览':'新增'"
          :visible.sync="dialogVisible"
          width="55%">
          <div>
            <el-form ref="form" :model="form" label-width="80px">
                <el-col :span="24" v-if="!isshow">
                  <el-form-item label="消息类型">
                    <el-radio-group v-model="form.messageType">
                      <el-radio v-for="(item,index) in newstypelist" :key="index" :label="item.typeCode">{{ item.typeName }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="isshow">
                  <el-form-item label="消息状态">
                    <el-radio-group v-model="form.messageStateName">
                      <el-radio  label="已创建">已创建</el-radio>
                      <el-radio  label="已发送">已发送</el-radio>
                      <el-radio  label="已撤销">已撤销</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                 <el-form-item label="标题">
                   <el-input v-model="form.messageTitle" placeholder="请输入标题" size="small"></el-input>
                 </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="内容类型">
                  <el-radio-group v-model="form.contentType">
                      <el-radio  label="text">text</el-radio>
                      <el-radio  label="html">html</el-radio>
                      <!-- <el-radio  label="已撤销">已撤销</el-radio> -->
                    </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                 <el-form-item label="消息内容">
                   <el-input v-if="form.contentType=='text'" v-model="form.messageContent" type="textarea" placeholder="请输入消息内容" size="small"></el-input>
                   <Tinymce ref="Tinymce" v-else v-model="form.messageContent" :height="150"></Tinymce>
                 </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="接收用户">
                  <el-radio-group v-model="form.radio">
                    <el-radio label="1">全体用户</el-radio>
                    <el-radio label="2">指定用户</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="form.radio=='2'">
                <el-form-item label="用户">
                  <el-select v-model="treeData" multiple size="small" style="width: 100%;" @remove-tag="removetag">
                    <el-option value="treeDataValue" label="label" style="height: auto">
                      <el-tree
                        ref="tree"
                        :props="propss"
                        :highlight-current="true"
                        @node-click="handleNodeClicks"
                        :load="loadNodes"
                        lazy>
                        <template slot-scope="{ node, data }">
                          <span :style="{cursor: data.userName ? 'pointer' : 'no-drop', fontSize: '14px'}">{{ node.label }}</span>
                        </template>
                      </el-tree>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                 <el-form-item label="创建时间">
                  <el-date-picker
                    size="small"
                    style="width: 100%;"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="form.createTime"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                 </el-form-item>
              </el-col>
              <el-col :span="24">
                 <el-form-item label="附件">
                   <img src="" alt=" ">
                 </el-form-item>
              </el-col>
              <el-col :span="24" v-if="isshow">
                 <el-form-item label="发送时间">
                   <el-input v-model="form.sendTime" placeholder="发送时间" size="small"></el-input>
                 </el-form-item>
              </el-col>
              <el-col :span="24" v-if="isshow">
                 <el-form-item label="撤回时间">
                   <el-input v-model="form.recoverTime" placeholder="撤回时间" size="small"></el-input>
                 </el-form-item>
              </el-col>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="quxiao" size="small">取 消</el-button>
            <el-button v-if="!isshow" type="primary" @click="submit" size="small">确 定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>

import Tinymce from '@/components/Tinymce'
import {getpingtainewsapi,geinewtypeapi,getarrzuzhiapi,getarrbumenapi,getuserlistapi,getaddnewsapi,postdelnewsapi,postfabunewsapi,
  postcexiaonewsapi,postupdatenewsapi
} from '@/api/system/UserNews'
import {exportexcel} from '@/utils/excel'
import TopTile from '@/components/TopTitle/index.vue'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTile,
    Tinymce
  },
  data() {
    return {
      issize: 'medium',
      title: '',
      tableData:[],
      loading: false,
      totalCounts: '',
      pageobj: {
        pageNo: 1,
        pageSize:20
      },
      newstypelist:[],
      dialogVisible:false,
      form: {},
      treeData:[],
      treeDataids:[],
      propss: {
        label: 'orgName',
        disabled:'disabled'
      },
      isshow:false
    };
  },

  async mounted() {
    this.xiangqinglist()
    const { data: { list } } = await geinewtypeapi()
    this.newstypelist = list
  },

  methods: {
    // 新增/修改确认
    async submit(){
      const {radio,...obj}=this.form
      const messageReceiver=this.treeDataids.map(ele=>ele.userNo).join(',')
      const typeGroup=this.newstypelist.find(ele=>ele.typeCode==this.form.messageType).typeGroup
      this.form.messageId?await postupdatenewsapi({
        createTime:this.form.createTime,hasAttachment:'0',isPublic:typeGroup=='公告消息'?'1':'0',messageAttachmentList:[],
        messageContent:this.form.messageContent,messageId:this.form.messageId,messageReceiver:this.form.radio=='2'?messageReceiver:'',
        messageTitle:this.form.messageTitle,messageType:this.form.messageType
      }).then(res=>{
        this.setmessage(res,'编辑成功')
      }):
      await getaddnewsapi({
        hasAttachment:'0',isPublic:typeGroup=='公告消息'?'1':'0',messageAttachmentList:[],messageReceiver:this.form.radio=='2'?messageReceiver:'',
        messageState:'0',contentLength:this.form.messageContent.length,...obj
      }).then(res=>{
        this.setmessage(res,'新增成功')
      })
       this.quxiao()
       this.xiangqinglist()
    },
    // 获取表格数据
    async xiangqinglist() {
      this.loading=true
      const { data: { list,totalCount } } = await getpingtainewsapi({
        pageNo:this.pageobj.pageNo-1,pageSize:this.pageobj.pageSize,messageTitle:this.title
      })
      this.tableData=list
      this.totalCounts=totalCount
      this.loading=false
    },
    // 编辑/浏览
    bianji(row, val) {
       this.dialogVisible=true
      this.form = { ...row }
      this.$nextTick(()=>this.$set(this.form, 'messageContent', row.messageContent))
       if(row.messageReceiver){
        this.$set(this.form,'radio','2')
        this.treeData=row.messageReceiverName.split(',')
        this.treeDataids=row.messageReceiver.split(',').map((ele,index)=>{
          return {
            userNo:ele,
            userName:this.treeData[index]
          }
        })
       }else{
        this.$set(this.form,'radio','1')
       }
       if(val=='look'){
        this.isshow=true
       }
    },
    // 取消
    quxiao(){
      this.dialogVisible = false
      this.form.messageContent=''
      this.form = {}
      this.$refs.Tinymce.clear();
      this.treeDataids=[]
      this.treeData=[]
    },
    // 下拉树点击
    handleNodeClicks(data, node, nodeData) {
      if(data.userName){
        this.treeDataids.push(data)
        this.treeData.push(data.orgName)
      }
    },
    // 移除下拉树
    removetag(val){
      this.treeDataids=this.treeDataids.filter(ele=>ele.userName!==val)
    },
    // 新增
    addnews() {
      this.dialogVisible = true
      // this.$set(this.form,'messageType',this.newstypelist[0].typeCode)
      this.$set(this.form, 'radio', '1')
      this.$set(this.form,'contentType','text')
    },
    // 删除
    delnews(row,val){
      this.$confirm(`此操作将${val=='shanchu'?'删除':val=='fabu'?'发布':'撤销'}该数据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if(val=='shanchu'){
            postdelnewsapi({messageId:row.messageId}).then(res=>{
              this.setmessage(res,'删除成功')
            })
          }else if(val=='fabu'){
            postfabunewsapi({messageId:row.messageId}).then(res=>{
              this.setmessage(res,'发布成功')
            })
          }else{
            postcexiaonewsapi({messageId:row.messageId}).then(res=>{
              this.setmessage(res,'撤销成功')
            })
          }
          this.xiangqinglist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      exportexcel('sst-microservice-biz/sst/message/platform/exportExcel',{
        messageTitle:this.title,
      },'平台消息中心数据')
    },
    // 刷新列表
    shuaxin() {
      this.xiangqinglist()
      this.$message.success('列表刷新成功')
    },
    // 重置
    chongzhi(){
      this.title=''
      this.xiangqinglist()
    },
    setmessage(res,name){
      this.$message({
        type:res.code=='200'?'success':'warning',
        message:res.code=='200'?name:res.message
      })
    },
    // 树组件懒加载
    async loadNodes(node, resolve) {
      if (node.level === 0) { // 初始的级数（最顶层）
        const {data:{list}}=await getarrzuzhiapi({pageNo: 0,pageSize: 1000})
        return resolve(list) // 最顶层数据渲染为region
      } else if (node.level > 0) {
        const { data: { list } } = await getarrbumenapi({ parentOrgNo: node.data.orgNo })
        if (!list.length) {
          const res = await getuserlistapi({ deptNo: node.data.orgNo })
          var userlist = res.data.list.map(ele => {
            return {
              ...ele,
              orgName:ele.userName
            }
          })
        }
        if(node.data.userName) return resolve([])
        return resolve(list.length?list:userlist)
      }
    },
  },
  watch:{
    dialogVisible(val){
      if(!val){
        this.isshow=false
        this.form.messageId=''
      }
    }
  }
};
</script>

<style scoped>
.PlatformNewsbox{
  height:100%;
  padding: 10px;
  .topbox{
    height: 80px;
    background-color: #fff;
    line-height: 80px;
    padding: 0 20px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    .leftspan{
      display: flex;
      span{
        margin-right: 10px;
        font-size: 14px;
        color: #606266;
      }
    }
  }
  .bodybox{
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .title{
      display: flex;
      justify-content: space-between;
      .butexp{
        display: flex;
        .moban{margin-right: 10px;}
      }
    }
    .table{
      height: 89%;
      margin-top: 10px;
      .status{
        display: inline-block;
        padding: 5px 10px;
        color: #fff;
        border-radius: 3px;
      }
      i{
        margin-right: 10px;
      }
    }
    .fenye{
      text-align: right;
      margin-top: 10px;
    }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
}
::v-deep .editor-custom-btn-container{
  display: none;
}
::v-deep .mce-container{
  width: 100%;
}
</style>